import { Injectable } from '@nestjs/common';
import * as COS from 'cos-nodejs-sdk-v5';

@Injectable()
export class UploadService {
  private readonly bucket = 'test-1254206734';
  private readonly region = 'ap-guangzhou';
  private cos: any; // 修改类型为any

  constructor() {
    this.cos = new (COS as any)({
      // 修改实例化方式
      SecretId: process.env.COS_SECRET_ID,
      SecretKey: process.env.COS_SECRET_KEY,
    });
  }

  async uploadFile(
    file: Express.Multer.File,
    phoneName: string,
  ): Promise<{ url: string }> {
    await this.cos.putObject({
      Bucket: this.bucket,
      Region: this.region,
      Key: phoneName,
      Body: file.buffer, // 直接使用 Buffer，不要转换
      ContentLength: file.size,
      ContentType: 'image/jpg', // 明确指定类型
      onProgress: (progress) => {
        console.log('上传进度:', progress);
      },
    });
    const url = `https://${this.bucket}.cos.${this.region}.myqcloud.com/${phoneName}`;
    return { url };
  }
}
